<?php

namespace app\admin\controller\census;

use app\common\controller\Backend;
use think\Session;
use think\Db;

/**
 * 店铺管理
 *
 * @icon fa fa-circle-o
 */
class Refund extends Backend
{

    /**
     * Refund模型对象
     * @var \app\admin\model\census\Refund
     */
    protected $model = null;
    protected $order_model = null;
    protected $goods_order_model = null;
    protected $order_item_model = null;
    protected $count_order_model = null;
    protected $shop_id = null;
    protected $refund_model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->shop_id = Session::get('shop');
        $this->model = new \app\admin\model\census\Refund;
        $this->order_model = new \app\admin\model\order\Order;
        $this->goods_order_model = new \app\admin\model\order\Goods;
        $this->order_item_model = new \app\admin\model\order\Item;
        $this->count_order_model = new \app\admin\model\census\Adate;
        $this->refund_model = new \app\admin\model\wanlshop\Refund;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("verifyList", $this->model->getVerifyList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['order'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            if ($list->total() > 0) {
                $list_data = $list->items();
                foreach ($list_data as $key => &$value) {
                    $conditions = [];
                    $conditions['o.shop_id'] = $value['id'];
                    $conditions['o.status'] = 'normal';
                    $conditions['r.createtime'] = [['>=',$value['order']['adatetime']],['<=',$value['order']['adatetime'] + 3600 * 24 - 1]];

                    //退款总额
                    $value['total_refund_amount'] = $this->order_model->alias('o')
                                                        ->join('wanlshop_refund r','r.order_id = o.id','left')
                                                        ->where($conditions)
                                                        ->sum('r.price');
                                                    
                    //退款笔数
                    $value['total_refund_count'] = $this->order_model->alias('o')
                                                        ->join('wanlshop_refund r','r.order_id = o.id','left')
                                                        ->where($conditions)
                                                        ->count('r.order_id');
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail()
    {
        $params = $this->request->get();
        $shop_id = $params['shop_id'];
        $createtime = $params['createtime'];

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $params = $this->request->get();
            $shop_id = $params['shop_id'];
            $createtime = $params['createtime'];
            $conditions = [];
            $conditions['r.shop_id'] = $shop_id;
            $conditions['r.status'] = 'normal';
            $conditions['r.createtime'] = [['>=',$createtime],['<=',$createtime + 3600 * 24 - 1]];
            $conditions[] = ['exp', Db::raw("FIND_IN_SET(og.goods_id, r.goods_ids) > 0 or FIND_IN_SET(oi.item_id, r.goods_ids) > 0")];

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            if (isset($params['filter']) && !empty($params['filter'])) {
                $filter = json_decode($params['filter'],true);
                if (isset($filter['order_no'])) {
                    $conditions['o.order_no'] =['like','%'.$filter['order_no'].'%'];
                }

                if (isset($filter['refund_way'])) {
                    $conditions['p.pay_way_id'] = 9;
                    if ($filter['refund_way'] == 0) {
                        $conditions['p.pay_way_id'] = ['in',[6,7,8]];
                    }elseif ($filter['refund_way'] == 2) {
                        $conditions['p.pay_way_id'] = ['in',[10,11,12]];
                    }
                }
            }

            $list = $this->refund_model->alias('r')
                    ->field('IFNULL(og.id,oi.id) as orderid,r.order_id as id,o.order_no,r.createtime,IFNULL(og.title,oi.name) as product_name,u.nickname,r.price,p.pay_way_id,IFNULL(og.gdtype,"2") as goods_type')
                    ->join('user u','u.id = r.user_id','left')
                    ->join('wanlshop_order o','o.id = r.order_id','left')
                    ->join('wanlshop_order_goods og','og.order_id = r.order_id','left')
                    ->join('wanlshop_order_item oi','oi.order_id = r.order_id','left')
                    ->join('wanlshop_pay_out_trade p','p.order_id = r.order_id','left')
                    ->where($conditions)
                    ->paginate($limit);

            $total = $list->total();
            $rows = $list->items();

            if ($total > 0) {
                foreach ($rows as $key => &$value) {
                    $value['refund_way'] = 1;
                    if(in_array($value['pay_way_id'],[6,7,8])){
                        $value['refund_way'] = 0;
                    }elseif(in_array($value['pay_way_id'],[10,11,12])){
                        $value['refund_way'] = 2;
                    }
                    $value['j_url'] = url('/order/goods/detail/ids/'.$value["orderid"]);
                    if ($value['goods_type'] == '1') {
                        $value['j_url'] = url('/order/treatment/detail/ids/'.$value["orderid"]);
                    }elseif ($value['goods_type'] == '2') {
                        $value['j_url'] = url('/order/item/detail/ids/'.$value["orderid"]);
                    }
                }
            }

            $result = array("total" => $total, "rows" => $rows);
            return json($result);
        }
        $this->assignconfig('shop_id', $shop_id);
        $this->assignconfig('createtime', $createtime);
        return $this->view->fetch();
    }
}
